package com.ea.eadp.nexus.test.pageDefinition;

import com.ea.eadp.nexus.test.common.PageOperation;
import com.ea.eadp.nexus.test.common.SystemProperties;
import com.ea.eadp.nexus.test.common.TestUtil;
import com.ea.eadp.test.shared.utility.RandomFactory;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.ExpectedCondition;
import org.openqa.selenium.support.ui.WebDriverWait;


/**
 * User: woodywu
 */
public class Signin_PC extends BasePage {
    public static final String uri = baseUri + TestUtil.SigninPcConnectURI();
    public static final String redirectURI = SystemProperties.instance().getProperty(SystemProperties.RedirectUri);

    public Signin_PC(WebDriver driver) {
        super(driver, Signin_PC.class);
    }

    public void navigate() {
        driver.switchTo().window(this.operationWindowHandle);
        log.info(uri);
        driver.get(uri);
    }

    public void navigate(String client_id, String locale, String redirectUri, String pc_machine_id) {
        driver.switchTo().window(this.operationWindowHandle);

        String signinUrl = baseUri + TestUtil.SigninPcConnectURI(client_id, locale, redirectUri, pc_machine_id);
        log.info(signinUrl);
        driver.get(signinUrl);
    }

    public void navigate(String uri) {
        driver.switchTo().window(this.operationWindowHandle);
        log.info(uri);
        driver.get(uri);
    }

    public void setSigninEmail(String email) {
        driver.switchTo().window(this.operationWindowHandle);
        log.info(email);
        SendKeyToElementAfterWait(driver, "email", email);
    }

    public void setSigninPassword(String password) {
        driver.switchTo().window(this.operationWindowHandle);
        log.info(password);
        SendKeyToElementAfterWait(driver, "password", password);
    }

    public void setUpgradeOriginID(String originID) {
        driver.switchTo().window(this.operationWindowHandle);
        log.info(originID);
        waitForWebElementPresent(By.id("originId"));
        PageOperation.SendKeyToElement(driver, "originId", originID);
    }

    /**
     * click "log in" button on sign in page, to get the error messages for email/password
     */
    public void clickLoginOnSigninPage() {
        driver.switchTo().window(this.operationWindowHandle);
        driver.findElement(By.cssSelector("#login-form > div.panel-action-area > #btnLogin > span > span")).click();
        PageOperation.WebDriverWait(driver, "online-general-error");
    }

    /**
     * click "log in" button on sign in page, redirect to 'about me' page to complete sign in
     */
    public void clickToSigninComplete() throws Exception {
        clickToSigninComplete(true);
    }

    public void clickToSigninComplete(boolean verification) throws Exception {
        driver.switchTo().window(this.operationWindowHandle);
        driver.findElement(By.cssSelector("#login-form > div.panel-action-area > #btnLogin > span > span")).click();
        if(verification == true) {
            Thread.sleep(5000);
            if (!TestUtil.getCurrentUrl(driver).contains(redirectURI) && !TestUtil.getCurrentUrl(driver).contains("s2")) {
                throw new Exception("validate goes to redirect uri.");
            }
        }
        //PageOperation.WebDriverWaitByXpath(driver, "//div[@id='mod-navigation']");
        //Assert.assertEquals(TestUtil.getCurrentUrl(driver).contains("about/me?fid="), true, "validate goes to 'about me' page.");
    }

    public void clickToSigninCompleteWithSpecific(String redirectURI) throws Exception {
        driver.switchTo().window(this.operationWindowHandle);
        driver.findElement(By.cssSelector("#login-form > div.panel-action-area > #btnLogin > span > span")).click();
        Thread.sleep(5000);
        if (!TestUtil.getCurrentUrl(driver).contains(redirectURI) && !TestUtil.getCurrentUrl(driver).contains("s2")) {
            throw new Exception("validate goes to redirect uri.");
        }
    }

    /**
     * get the status for 'log in' button on sign in page
     */
    public String getStatusForLogin() {
        driver.switchTo().window(this.operationWindowHandle);
        return driver.findElement(By.id("btnLogin")).getAttribute("class").toString();
    }

    public String getError() {
        driver.switchTo().window(this.operationWindowHandle);
        return driver.findElement(By.cssSelector("#loginForm > div.red-box-error")).getText();
    }

    /**
     * click "log in" button on sign in page, redirect to 's2' page to upgrade account
     */
    public void clickLoginToUpgradePage() throws Exception {
        driver.switchTo().window(this.operationWindowHandle);
        driver.findElement(By.cssSelector("#login-form > div.panel-action-area > #btnLogin > span > span")).click();
        PageOperation.WebDriverWaitByXpath(driver, "//form[@id='upgradeForm']");
        if (!TestUtil.getCurrentUrl(driver).contains("s2")) {
            throw new Exception("validate goes to 's2' page");
        }
    }

    /**
     * click "log in" button on sign in page, redirect to age up
     */
    public void clickLoginToAgeUpPage() throws Exception {
        driver.switchTo().window(this.operationWindowHandle);
        driver.findElement(By.cssSelector("#login-form > div.panel-action-area > #btnLogin > span > span")).click();
        PageOperation.WebDriverWaitByXpath(driver, "//div[@id='panel-profile']");
        if (!TestUtil.getCurrentUrl(driver).contains("s2")) {
            throw new Exception("validate goes to 's2' page");
        }
    }

    /**
     * click "log in" button on sign in page, redirect to 's2' page to nux
     */
    public void clickLoginToNuxPage() throws Exception {
        driver.switchTo().window(this.operationWindowHandle);
        driver.findElement(By.cssSelector("#login-form > div.panel-action-area > #btnLogin > span > span")).click();
        PageOperation.WebDriverWaitByXpath(driver, "//form[@id='nuxForm']");
        if (!TestUtil.getCurrentUrl(driver).contains("s2")) {
            throw new Exception("validate goes to 's2' page");
        }
    }

    /**
     * click "next" button on upgrade page, redirect to s3 page
     */
    public void clickNextToComplete() throws Exception {
        driver.switchTo().window(this.operationWindowHandle);
        PageOperation.WebDriverWaitByXpath(driver, "//form[@id='upgradeForm']/div[4]/a[2]/span/span");
        driver.findElement(By.xpath("//form[@id='upgradeForm']/div[4]/a[2]/span/span")).click();
        PageOperation.WebDriverWaitByXpath(driver, "//form[@id='webnewform']");
        if (!TestUtil.getCurrentUrl(driver).contains("s3")) {
            throw new Exception("validate goes to 's3' page");
        }
    }

    /**
     * click "next" button on upgrade page, to get the error message for origin id
     */
    public void clickNextOnUpgradePage() throws Exception {
        driver.switchTo().window(this.operationWindowHandle);
        PageOperation.WebDriverWaitByXpath(driver, "//form[@id='upgradeForm']/div[4]/a[2]/span/span");
        driver.findElement(By.xpath("//form[@id='upgradeForm']/div[4]/a[2]/span/span")).click();
        PageOperation.WebDriverWaitByCssSelector(driver, "#origin-id-container");
    }

    public void setFirstName(String firstName) {
        driver.switchTo().window(this.operationWindowHandle);
        log.info(firstName);
        PageOperation.SendKeyToElement(driver, "firstName", firstName);
    }

    public void setLastName(String lastName) {
        driver.switchTo().window(this.operationWindowHandle);
        log.info(lastName);
        PageOperation.SendKeyToElement(driver, "lastName", lastName);
    }

    /**
     * click "next" button on create profile page, redirect to 'about me' page to complete upgrade
     */
    public void clickToUpgradeComplete() throws Exception {
        driver.switchTo().window(this.operationWindowHandle);
        PageOperation.WebDriverWaitByXpath(driver, "//div[@id='panel-profile-settings']/div[4]/a[1]/span/span");
        driver.findElement(By.xpath("//div[@id='panel-profile-settings']/div[4]/a[1]/span/span")).click();
        PageOperation.WebDriverWaitCurrentUrlContains(driver, redirectURI);
    }

    /**
     * get error for origin id during upgrade account
     */
    public String getErrorForOriginID() throws Exception {
        driver.switchTo().window(this.operationWindowHandle);
        WebDriverWait wait = new WebDriverWait(driver, 10, 1000);
        wait.until(
                new ExpectedCondition<Boolean>() {
                    public Boolean apply(WebDriver driver) {
                        return driver.findElement(By.xpath("//li[@id='origin-id-container']/div[1]/span[3]")).getText().trim().length() > 5;
                    }
                });
        return driver.findElement(By.xpath("//li[@id='origin-id-container']/div[1]/span[3]")).getText();
    }

    /**
     * get attribute 'MaxLength' for Origin ID, confirm if it is '16'
     */
    public String getMaxLengthForOriginID() {
        driver.switchTo().window(this.operationWindowHandle);
        return driver.findElement(By.id("originId")).getAttribute("maxlength");
    }

    public void setVisibility(String visibility) throws Exception {
        driver.switchTo().window(this.operationWindowHandle);
        log.info(visibility);
        String cssSelector = "#clientreg_friend_visibility";
        PageOperation.SelectCssDropDownItem(driver, cssSelector, visibility);
    }

    public String getPoweredBy() {
        return getElementStringByXPath("//div[@id='login-form']/div[1]/span");
    }

    public String getEmailLabel() {
        return getElementStringByXPath("//div[@id='login-form']/div[2]/div/label");
    }

    public String getPasswordLabel() {
        return getElementStringByXPath("//div[@id='login-form']/div[3]/div/label");
    }

    public String getForgotPasswordLink() {
        return getElementStringByXPath("//div[@id='forgot-password-section']/a");
    }

    public String getLoginButtonString() {
        return getElementStringByXPath("//a[@id='btnLogin']/span/span");
    }

    public String getRememberMeLabel() {
        return getElementStringByXPath("//label[@id='label-rememberMe']");
    }

    public String getLoginInvisibleLabel() {
        return getElementStringByXPath("//label[@id='label-loginInvisible']");
    }

    public String getCreateAccountButtonString() {
        return getElementStringByXPath("//form[@id='loginForm']/div[8]/p/a");
    }

    public void clickSkipEmailVerification() throws Exception {
        driver.switchTo().window(this.operationWindowHandle);
        driver.findElement(By.xpath("//div[@id='panel-profile-confirmation']/div[3]/a[2]/span/span")).click();
        WebDriverWait wait = new WebDriverWait(driver, 30, 1000);
        wait.until(new ExpectedCondition<Boolean>() {
            public Boolean apply(WebDriver driver) {
                return TestUtil.getCurrentUrl(driver).contains(redirectURI);
            }
        });
    }

    public void setCaptcha(String value) {
        driver.switchTo().window(this.operationWindowHandle);
        log.info(value);
        PageOperation.SendKeyToElementAfterWait(driver, "recaptcha_response_field", value);
    }

    public String getUpgradeHeader() {
        return getElementStringByXPath("//div[@id='panel-profile-upgrade']/div[1]/div/h2");
    }

    public void ClickContinueOnNux(Boolean hasProfile) throws Exception{
        driver.switchTo().window(this.operationWindowHandle);
        driver.findElement(By.xpath("//a[@id='submit-btn']/span/span")).click();
        Thread.sleep(2000);
        if(hasProfile){
            if(!TestUtil.getCurrentUrl(driver).contains("s3"))
                throw new Exception("validate goes to 's3' page");
        }
        else {
            if(!TestUtil.getCurrentUrl(driver).contains(redirectURI))
                throw new Exception("validate goes to redirect uri");
        }
    }

    public String getEmailByPath(String path) {
        return getElementStringByXPath(path);
    }

    public String getContinueButtonString(String path) {
        return getElementStringByXPath(path);
    }

    public static void SendKeyToElementAfterWait(WebDriver driver, String elementId, String key) {
        PageOperation.WebDriverWait(driver, elementId);
        SendKeyToElement(driver, elementId, key);
    }
    public static void SendKeyToElement(WebDriver driver, String elementId, String key) {
        driver.findElement(By.id(elementId)).clear();
        driver.findElement(By.id(elementId)).click();
        driver.findElement(By.id(elementId)).sendKeys(key);
    }
    public void checkRememberMe(boolean check) {
        driver.switchTo().window(this.operationWindowHandle);
        WebElement checkbox = driver.findElement(By.id("rememberMe"));
        WebElement parent = (WebElement) ((JavascriptExecutor) driver).executeScript("return arguments[0].parentNode;", checkbox);
        if (check && !checkbox.isSelected()) {
            parent.click();
        } else if (!check && checkbox.isSelected()) {
            parent.click();
        }
    }

    public void clickCreateAccountButton() throws Exception{
        driver.switchTo().window(this.operationWindowHandle);
        driver.findElement(By.xpath("//a[@class='registration-link']")).click();
        Thread.sleep(2000);
    }
}